import frappe
from frappe import _

@frappe.whitelist(allow_guest=True)
def unified_register(
    email,
    password=None,
    full_name=None,
    provider=None,
    third_party_id=None,
    avatar_url=None
):
    # email格式校验略

    user = frappe.db.get("User", {"email": email})

    # 第三方注册/登录分支
    if provider and third_party_id:
        if user:
            # 已有用户，绑定第三方信息
            frappe.db.set_value("User", user.name, "third_party_provider", provider)
            frappe.db.set_value("User", user.name, "third_party_id", third_party_id)
            # 可选：更新头像等
            if avatar_url:
                frappe.db.set_value("User", user.name, "user_image", avatar_url)
            return {"message": "login", "email": email}
        else:
            # 注册新用户（无密码，设定随机密码防止传统登录）
            user_doc = frappe.get_doc({
                "doctype": "User",
                "email": email,
                "first_name": full_name or email,
                "enabled": 1,
                "third_party_provider": provider,
                "third_party_id": third_party_id,
                "new_password": frappe.generate_hash(),
                "user_image": avatar_url,
            })
            user_doc.insert(ignore_permissions=True)
            user_doc.add_roles("Website User")
            return {"message": "register", "email": email}

    # 普通邮箱密码注册分支
    elif password:
        if user:
            frappe.throw(_("User already exists"))
        user_doc = frappe.get_doc({
            "doctype": "User",
            "email": email,
            "first_name": full_name or email,
            "enabled": 1,
            "new_password": password,
        })
        user_doc.insert(ignore_permissions=True)
        # user_doc.add_roles("Website User")
        return {"message": "register", "email": email}

    else:
        frappe.throw(_("Invalid parameters"))
